package com.innovation.ic.im.end.base.thread.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.im.end.base.model.im_erp9.GroupMessage;
import com.innovation.ic.im.end.base.model.im_erp9.GroupMessageReceiver;
import com.innovation.ic.im.end.base.model.im_erp9.RefGroupAccount;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.enums.AvailableStatusEnum;
import com.innovation.ic.im.end.base.pojo.enums.ReadStatusEnum;
import com.innovation.ic.im.end.base.pojo.im_erp9.AccountGroupLastContactPojo;
import com.innovation.ic.im.end.base.service.helper.ServiceImplHelper;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import lombok.SneakyThrows;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc   保存默认群组撤回消息对象内容
 * @author linuo
 * @time   2022年10月18日10:17:31
 */
public class SaveRetractionGroupMessageReceiverThread extends AbstractThread implements Runnable {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String exchange;
    private Long waitingLockTime;
    private Integer groupMessageId;

    public SaveRetractionGroupMessageReceiverThread(String exchange, Long waitingLockTime, Integer groupMessageId, GroupMessage groupMessage, CuratorFramework curatorFramework) {
        this.exchange = exchange;
        this.waitingLockTime = waitingLockTime;
        this.groupMessageId = groupMessageId;
        this.groupMessage = groupMessage;
        this.curatorFramework = curatorFramework;
    }

    @SneakyThrows
    @Override
    public void run() {
        // 保存群组系统消息数据并推送rabbitMq消息
        List<String> list = new ArrayList<>();
        list.add(groupMessage.getFromUserAccount());
        ServiceResult<List<RefGroupAccount>> serviceResult = ServiceImplHelper.getRefGroupAccountService().findByGroupIdAndNotInList(groupMessage.getGroupId(), list);
        if (null != serviceResult && null != serviceResult.getResult()) {
            List<RefGroupAccount> refGroupAccountList = serviceResult.getResult();
            logger.info("需要给群组refGroupAccountList:[{}]中的用户记录系统消息", JSONObject.toJSONString(refGroupAccountList));
            for (int i = 0; i < refGroupAccountList.size(); i++) {
                GroupMessageReceiver groupMessageReceiver = new GroupMessageReceiver();
                groupMessageReceiver.setGroupId(groupMessage.getGroupId());
                groupMessageReceiver.setGroupMessageId(groupMessageId);
                groupMessageReceiver.setToUserAccount(refGroupAccountList.get(i).getUsername());
                groupMessageReceiver.setToUserRealName(getUserRealNameByAccount(refGroupAccountList.get(i).getUsername()));
                groupMessageReceiver.setRead(ReadStatusEnum.READ.getCode());
                groupMessageReceiver.setToUserAvailable(AvailableStatusEnum.AVAILABLE.getCode());
                ServiceImplHelper.getGroupMessageReceiverService().saveGroupMessageReceiver(groupMessageReceiver);

                // 处理账号和群组的操作表数据
                ServiceImplHelper.getRefGroupAccountOperationService().handleRefGroupAccountOperationData(groupMessage.getGroupId(), refGroupAccountList.get(i).getUsername(), curatorFramework, waitingLockTime);
            }

            // 推送rabbitMq消息
            // 查询当前默认群组中的用户账号
            ServiceResult<List<String>> result = ServiceImplHelper.getRefGroupAccountService().getGroupAccounts(groupMessage.getGroupId());
            if(result != null && result.getResult() != null){
                List<String> userNames = result.getResult();
                for (int i = 0; i < userNames.size(); i++) {
                    String userName = userNames.get(i);
                    // 推送rabbitMq消息
                    ServiceResult<List<AccountGroupLastContactPojo>> lastContact = ServiceImplHelper.getUserGroupService().findLastContact(userName);
                    if(lastContact != null && lastContact.getResult() != null){
                        String json = JSON.toJSONString(lastContact);
                        // 推送消息
                        logger.info("将消息推送给用户:[{}]的mq队列中,内容为:[{}]", userName, json);
                        try {
                            ServiceImplHelper.getRabbitMqManager().basicPublish(exchange, userName, null, json.getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}